<template>
  <div class="trade-record-container">
    <!-- 页面标题 -->
    <div class="page-header mb-6">
      <h1 class="text-2xl font-bold text-gray-800">支付交易记录</h1>
      <p class="text-gray-500 mt-1">展示所有保费支付记录，支持按保单号和支付状态筛选</p>
    </div>

    <!-- 搜索与筛选区域 -->
    <el-card class="filter-card shadow-sm mb-6">
      <el-form :inline="true" :model="searchForm" class="search-form" size="small">
        <!-- 保单号模糊搜索 -->
        <el-form-item label="保单编号" class="w-[300px]">
          <el-input
              v-model="searchForm.policyId"
              placeholder="请输入保单号（模糊查询）"
              clearable
              @keyup.enter="fetchTradeList"
          ></el-input>
        </el-form-item>

        <!-- 支付状态筛选 -->
        <el-form-item label="支付状态">
          <el-select
              v-model="searchForm.paymentStatus"
              placeholder="全部状态"
              clearable
              style="width: 100px"
          >
            <el-option label="待支付" value="1"></el-option>
            <el-option label="支付成功" value="2"></el-option>
            <el-option label="支付失败" value="3"></el-option>
          </el-select>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button
              type="primary"
              @click="fetchTradeList"
              icon="el-icon-search"
              class="mr-2"
          >
            查询
          </el-button>
          <el-button
              type="default"
              @click="resetSearch"
              icon="el-icon-refresh"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 交易记录表格 -->
    <el-card class="table-card shadow-sm">
      <div class="table-container">
        <el-table
            :data="tradeList"
            border
            stripe
            v-loading="loading"
            element-loading-text="加载交易记录中..."
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(255, 255, 255, 0.8)"
            style="width: 100%"
        >
          <!-- 支付记录ID -->
          <el-table-column
              prop="paymentId"
              label="支付记录ID"
              width="200"
              align="center"
              fixed="left"
          >
            <template #default="scope">
              <span class="text-blue-600 hover:underline cursor-pointer" @click="copyText(scope.row.paymentId)">
                {{ scope.row.paymentId }}
              </span>
            </template>
          </el-table-column>

          <!-- 保单号 -->
          <el-table-column
              prop="policyId"
              label="关联保单号"
              width="180"
              align="center"
          >
            <template #default="scope">
              <span class="font-medium">{{ scope.row.policyId }}</span>
            </template>
          </el-table-column>

          <!-- 支付金额 -->
          <el-table-column
              prop="paymentAmount"
              label="支付金额(元)"
              width="120"
              align="right"
          >
            <template #default="scope">
              <span :class="scope.row.paymentStatus === 2 ? 'text-red-600 font-medium' : 'text-gray-800'">
                {{ scope.row.paymentAmount.toFixed(2) }}
              </span>
            </template>
          </el-table-column>

          <!-- 支付状态 -->
          <el-table-column
              prop="paymentStatus"
              label="支付状态"
              width="120"
              align="center"
          >
            <template #default="scope">
              <el-tag
                  :type="getStatusTagType(scope.row.paymentStatus)"
                  size="small"
              >
                {{ getStatusDesc(scope.row.paymentStatus) }}
              </el-tag>
            </template>
          </el-table-column>

          <!-- 支付宝交易号 -->
          <el-table-column
              prop="alipaySandboxTradeNo"
              label="支付宝交易号"
              width="220"
              align="center"
          >
            <template #default="scope">
              <span v-if="scope.row.alipaySandboxTradeNo" class="text-gray-700">
                {{ scope.row.alipaySandboxTradeNo }}
              </span>
              <span v-else class="text-gray-400">-</span>
            </template>
          </el-table-column>

          <!-- 支付时间 -->
          <el-table-column
              prop="paymentTime"
              label="支付时间"
              width="180"
              align="center"
          >
            <template #default="scope">
              <span v-if="scope.row.paymentTime" class="text-gray-700">
                {{ formatDateTime(scope.row.paymentTime) }}
              </span>
              <span v-else class="text-gray-400">-</span>
            </template>
          </el-table-column>

          <!-- 订单标题 -->
          <el-table-column
              prop="subject"
              label="订单标题"
              min-width="200"
              align="center"
          >
            <template #default="scope">
              <span class="text-gray-700">{{ scope.row.subject }}</span>
            </template>
          </el-table-column>

          <!-- 操作列 -->
          <el-table-column
              label="操作"
              width="150"
              align="center"
              fixed="right"
          >
            <template #default="scope">
              <!-- 待支付订单：重新支付按钮 -->
              <el-button
                  v-if="scope.row.paymentStatus === 1"
                  type="primary"
                  size="mini"
                  icon="el-icon-money"
                  @click="handleRePay(scope.row)"
              >
                去支付
              </el-button>

              <!-- 已支付/失败订单：查看详情按钮 -->
              <el-button
                  v-else
                  type="text"
                  size="mini"
                  icon="el-icon-view"
                  class="text-blue-600"
                  @click="handleViewDetail(scope.row)"
              >
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页控件（匹配后端PageInfo格式） -->
      <div class="pagination-container mt-6 flex justify-end items-center">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.pageNum"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            :pager-count="5"
            layout="total, sizes, prev, pager, next, jumper"
            background
        ></el-pagination>
      </div>
    </el-card>

    <!-- 交易详情弹窗 -->
    <el-dialog
        title="交易记录详情"
        v-model="detailDialogVisible"
        width="600px"
        :close-on-click-modal="false"
    >
      <div class="detail-content" v-loading="detailLoading">
        <div class="detail-section mb-4">
          <h3 class="section-title text-lg font-semibold mb-3">基础信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="支付记录ID">{{ currentTrade.paymentId }}</el-descriptions-item>
            <el-descriptions-item label="关联保单号">{{ currentTrade.policyId }}</el-descriptions-item>
            <el-descriptions-item label="订单标题">{{ currentTrade.subject }}</el-descriptions-item>
            <el-descriptions-item label="支付金额">{{ currentTrade.paymentAmount ? currentTrade.paymentAmount.toFixed(2) + ' 元' : '-' }}</el-descriptions-item>
            <el-descriptions-item label="支付状态">{{ currentTrade.paymentStatus ? getStatusDesc(currentTrade.paymentStatus) : '-' }}</el-descriptions-item>
            <el-descriptions-item label="支付宝交易号">{{ currentTrade.alipaySandboxTradeNo || '-' }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="detail-section">
          <h3 class="section-title text-lg font-semibold mb-3">时间信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="支付时间">{{ currentTrade.paymentTime ? formatDateTime(currentTrade.paymentTime) : '-' }}</el-descriptions-item>
            <el-descriptions-item label="最后更新时间">{{ currentTrade.updateTime ? formatDateTime(currentTrade.updateTime) : '-' }}</el-descriptions-item>
            <el-descriptions-item label="支付备注" :span="2">{{ currentTrade.paymentRemark || '-' }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElLoading } from 'element-plus';
import hxxp from "@/utils/hxxp";

// 路由实例
const router = useRouter();

// 状态管理
const tradeList = ref([]); // 交易记录列表
const loading = ref(false); // 列表加载状态
const detailDialogVisible = ref(false); // 详情弹窗显示状态
const detailLoading = ref(false); // 详情加载状态
const currentTrade = ref({}); // 当前查看的交易记录

// 搜索表单数据
const searchForm = reactive({
  policyId: '', // 保单号模糊搜索
  paymentStatus: '' // 支付状态筛选（1-待支付，2-成功，3-失败）
});

// 分页参数（与后端PageInfo格式匹配）
const pagination = reactive({
  pageNum: 1, // 当前页码
  pageSize: 5, // 每页条数
  total: 0 // 总记录数
});

/**
 * 页面加载时初始化交易列表
 */
onMounted(() => {
  fetchTradeList();
});

/**
 * 获取交易记录列表（核心接口调用）
 */
const fetchTradeList = () => {
  loading.value = true;
  const params = {
    pageNum: pagination.pageNum,
    pageSize: pagination.pageSize,
    policyId: searchForm.policyId,
    paymentStatus: searchForm.paymentStatus ? Number(searchForm.paymentStatus) : undefined
  };

  hxxp.get('/aiPay/getAiPayList', { params })
      .then(response => {
        loading.value = false;
        if (response.code === 100200) {
          const data = response.data;
          tradeList.value = data.list; // 交易记录列表
          // 同步分页参数（与后端返回的PageInfo对齐）
          pagination.total = data.total;
          pagination.pageNum = data.pageNum;
          pagination.pageSize = data.pageSize;
        } else {
          ElMessage.error('查询交易记录失败：' + (response.msg || '未知错误'));
        }
      })
      .catch(error => {
        loading.value = false;
        console.error('查询交易记录异常：', error);
        ElMessage.error('网络异常，查询交易记录失败');
      });
};

/**
 * 重置搜索条件
 */
const resetSearch = () => {
  searchForm.policyId = '';
  searchForm.paymentStatus = '';
  pagination.pageNum = 1;
  fetchTradeList();
};

/**
 * 分页大小变更
 */
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  pagination.pageNum = 1; // 重置为第一页
  fetchTradeList();
};

/**
 * 当前页码变更
 */
const handleCurrentChange = (page) => {
  pagination.pageNum = page;
  fetchTradeList();
};

/**
 * 支付状态值转描述
 */
const getStatusDesc = (status) => {
  const statusMap = {
    1: '待支付',
    2: '支付成功',
    3: '支付失败'
  };
  return statusMap[status] || '未知状态';
};

/**
 * 支付状态标签类型
 */
const getStatusTagType = (status) => {
  const typeMap = {
    1: 'warning', // 待支付-警告色
    2: 'success', // 支付成功-成功色
    3: 'danger'   // 支付失败-危险色
  };
  return typeMap[status] || 'default';
};

/**
 * 格式化日期时间（处理后端返回的ISO格式时间）
 */
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '';
  // 处理后端返回的 "2025-09-22T17:23:24" 格式，转为 "2025-09-22 17:23:24"
  return dateTimeStr.replace('T', ' ');
};

/**
 * 复制文本到剪贴板
 */
const copyText = (text) => {
  navigator.clipboard.writeText(text)
      .then(() => {
        ElMessage.success('复制成功');
      })
      .catch(() => {
        ElMessage.error('复制失败，请手动复制');
      });
};

/**
 * 查看交易详情
 */
const handleViewDetail = (trade) => {
  currentTrade.value = {...trade};
  detailDialogVisible.value = true;
};

/**
 * 待支付订单重新支付
 */
const handleRePay = (trade) => {
  // 跳转到支付页面，携带保单号和金额
  router.push({
    path: '/needPayList', // 待缴费列表页面（或直接跳支付接口）
    query: {
      policyId: trade.policyId,
      paymentAmount: trade.paymentAmount.toString()
    }
  });
  ElMessage.info('正在跳转到支付页面...');
};
</script>

<style scoped>
.trade-record-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
  overflow: auto;
}

.page-header {
  margin-bottom: 20px;
}

.filter-card {
  border-radius: 8px;
  padding: 15px;
  background: #fff;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
}

.table-card {
  border-radius: 8px;
  background: #fff;
  padding: 20px;
}

.table-container {
  overflow-x: auto;
}

.pagination-container {
  padding: 10px 0 0;
}

/* 详情弹窗样式 */
.detail-content {
  padding: 10px 0;
}

.detail-section {
  margin-bottom: 15px;
}

.section-title {
  color: #333;
  border-left: 4px solid #409eff;
  padding-left: 8px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }

  .el-form-item {
    width: 100% !important;
  }
}

@media (max-width: 768px) {
  .trade-record-container {
    padding: 10px;
  }

  .table-card {
    padding: 10px;
  }

  .el-table-column {
    min-width: 120px;
  }
}
</style>